package netapp.tcp_4;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class ThreadSocket implements Runnable {
    private Socket accept;
    public ThreadSocket(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            // 二、读取客户端发送的数据
            BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
            // 将获取的字节数据写入到文件中
            bos = new BufferedOutputStream(new FileOutputStream("AdvancedCode/dest/" + UUID.randomUUID()+ ".jpg"));

            byte[] bytes = new byte[1024 * 10];
            int count;
            while ((count = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, count);
                bos.flush();
            }
            // 禁用socket输入流
            accept.shutdownInput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭本地输出流
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        try {
            // 三、向客户端写出反馈数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
            bw.write("上传成功");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            try {
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
